<?php

namespace app\index\service;

use app\common\model\Trade;
use app\index\model\UM as UM;
use app\index\service\payments\CardPaymentService;
use app\index\traits\PaymentProxyTrait;
use app\index\traits\PaymentTrait;
use ary\Ary;
use ShidianUtil\Exception\DataNotExistException;
use think\exception\ValidateException;

/**
 * Class SourceBuyoutService
 * @package app\index\service
 */
class SourceBuyoutService
{
    use PaymentTrait;
    use PaymentProxyTrait;

    private TradeSourceService $tradeSourceService;

    public function __construct(TradeSourceService $tradeSourceService)
    {

        $this->tradeSourceService = $tradeSourceService;
    }

    /**
     * 买断
     * @param UM $user
     * @param int $tradeId
     * @param array $params
     * @return Trade
     */
    public function modify(UM $user, int $tradeId, array $params): Trade
    {
        $memberId = $user->id;
        $companyId = $user->companyId;
        $userPersonnelId = $user->userPersonnelId;

        $record = Trade::field(true)
            ->where('id', $tradeId)
            ->where('memberId', $memberId)
            ->where('tradeType', TRADE_SOURCE)
            ->find();

        if (is_null($record)) {
            throw new DataNotExistException('该订单不存在或已被删除');
        }

        $attach = $record->attach;
        $orderId = $attach['aryOrderId'] ?? null;
        $sourceId = $record->sourceId;


        // 查询并计算价格，
        $data = ['source_id' => $sourceId];
        $response = $this->getAry()->getSourceDetail($data);
        $decodeContents = $response->getDecodeContentsOrThrow('无法获取案源信息，请稍后再试');

        $source = $decodeContents['data'];

        $unitPrice = $source['unit_price'] ?? null;
        $totalNum = $source['total_num'] ?? null;
        $soldNum = $source['sold_num'] ?? null;
        if (!is_numeric($totalNum) || !is_numeric($soldNum) || !is_numeric($unitPrice)) {
            throw new ValidateException('案源信息不正确，请稍后再试');
        }
        if ($unitPrice < 1) {
            throw new ValidateException('该案源信息不正确，请稍后再试');
        }
        $surplusNum = $totalNum - $soldNum;
        if ($surplusNum <= 0) {
            throw new ValidateException('该案源已售罄');
        }

        $payAmount = $surplusNum * $unitPrice;


        $proxyCard = false;

        // 公司账户
        if (is_id($userPersonnelId)) {

            // 检查是否存在代付公司，并且代付余额充足
            $proxyCard = $this->checkProxyProxyAndBalance($memberId, $companyId, $userPersonnelId, PAYMENT_CARD, $payAmount);
        }

        // 不能代付时检查是否可以自己支付
        if (!$proxyCard) {

            if (!$this->getCardPaymentService()->isEnableTransfer($memberId)) {
                throw new ValidateException('您的获客卡账户暂时不可用，请联系管理员');
            }

            // 用户账户的余额是否充足
            $balance = $this->getCardPaymentService()->getBalance($memberId);
            if ($balance < $payAmount) {
                throw new ValidateException('您的获客卡余额不足，当前余额' . $balance);
            }
        }


        // 调用案如云，买断
        $this->aryBuyout($orderId, $memberId);

        // 调用成功后，立即创建案源买断订单，并立即支付
        $trade = $this->tradeSourceService->buyout($user, $record, $params, $source);

        // 判断代付
        if ($proxyCard) {

            // 代付，并允许欠费
            $this->getProxyPayment($trade->payMethod)->proxyCompanyPay($trade, $companyId, $userPersonnelId, true);
        } else {

            // 立即进行支付，并允许欠费
            $this->getPayment($trade->payMethod)->pay($trade, true);
        }

        return $record;
    }

    private function getCardPaymentService(): CardPaymentService
    {
        return app(CardPaymentService::class);
    }

    private function aryBuyout($orderId, $userId)
    {
        $data = [
            'order_id' => $orderId,
            'user_id' => $userId,
        ];
        $response = $this->getAry()->buyout($data);

        return $response->getDecodeContentsOrThrow('购买失败');
    }

    private function getAry(): Ary
    {
        return app(Ary::class);
    }
}
